using System;
using System.Collections;
using System.Xml;
using Flaschengeist.DataAccess;
using Flaschengeist.Entities;
using UnityEngine;

namespace Flaschengeist.Processes 
{
	public class LoadLevelInfo : MonoBehaviour
	{
		private XmlRpc xmlrpc;
		private Level level;
		
		public void Start()
		{	
			xmlrpc = gameObject.AddComponent<XmlRpc>();
			xmlrpc.Completed += LoadCompleted;		
		}
		
		private void LoadCompleted(string xml)
		{			
			foreach (XmlNode node in xml.GetRecord())
			{
				if (node.HasChildNodes)
				{							
					if(node.FirstChild.InnerText == "WorldId")
						level.WorldId = int.Parse(node.LastChild.GetValueFromNode());
					
					if(node.FirstChild.InnerText == "Worldname")
						level.World = node.LastChild.GetValueFromNode();	
					
					if(node.FirstChild.InnerText == "Track")
						level.Track = node.LastChild.GetValuesFromNode();
					
					if(node.FirstChild.InnerText == "MaxFillLevel")
						level.MaxFillLevel = float.Parse(node.LastChild.GetValueFromNode());
					
					if(node.FirstChild.InnerText == "Scale")
						level.Scale = node.LastChild.GetValuesFromNode();
				}
			}
				
			Debug.Log("Finish load level info");			
			Completed(level);
		}
		
		public void Process(Level level)
		{		
			Debug.Log("Start load level info");
			this.level = level;
			
			var parameter = new Hashtable();
			parameter.Add("id", level.Id);
			xmlrpc.Process("getLevel", parameter);
		}
			
		public event Action<Level> Completed;	
	}
}

